#!/bin/sh

set -e

. /etc/utils.sh
. $(dirname $0)/Config.sh
. $(dirname $0)/utils.sh

error=

cleanup()
{
  umount /mnt || echo but no matter
}

usbstick()
{
  file=/mnt/diag_test_file
  want=4289204007

  blkdev=$(find_usb_blkdev)
  if [ -z "$blkdev" ]; then
    error="no USB mass storage device connected"
    return 1
  fi

  umount /mnt || echo but no matter
  run fdisk -l $blkdev
  run mount -t vfat ${blkdev}1 /mnt
  run rm -f $file
  echo "This file must have these exact letters, please do not modify" > $file
  sync
  run umount /mnt
  run mount -t vfat ${blkdev}1 /mnt
  cksum=$(cksum $file)
  sum=${cksum%% *}
  if [ "$sum" != $want ]; then
    error="cksum mismatch, wanted $want, got '$sum'"
    return 1
  fi
  run rm -f $file
  run umount /mnt
  return 0
}

usb3disk()
{
  # do a read test from the disk, expect at least 40 MB/sec
  blkdev=$(find_usb_blkdev)
  if [ -z "$blkdev" ]; then
    error="no USB mass storage device connected"
    return 1
  fi

  # this runs dd and prints xfer rate several times as the 1st dd runs
  f=/tmp/dd1
  dd if=$blkdev bs=65536 count=10000 2>$f |
  for n in `seq 1 10`; do dd bs=65536 count=1000 of=/dev/null; done

  # eg: 65536000 bytes transferred in 1.522 secs (43059132 bytes/sec)
  dd1=$(tail -n 1 /tmp/dd1)
  dd1=${dd1%% bytes/sec*}
  dd1=${dd1##* secs (}
  if [ "$dd1" -lt $usb_min_bps ]; then
    error="wanted $usb_min_bps b/s or more, got $dd1 b/s"
    return 1
  fi
  result="$dd1 bytes/sec"
  return 0
}

case "$1" in
  diag | quick)
    if usb3disk; then
      echo PASS $result
    else
      echo FAIL "$error"
    fi
    ;;
  *)
    echo "Usage: $0 {diag|quick}"
    exit 1
esac
